'use strict'

const Controller = require('egg').Controller;
const FormStream = require('formstream');

class zinvest extends Controller {

    async forward() {

        const { host, prefix } = this.config.apiServer;

        let url = this.ctx.request.url;
       
        url = url.replace(new RegExp(prefix), "");

        

        let params = Object.assign({}, this.ctx.request.body, this.ctx.query);

        //console.log('---------------------');
     
        //console.log(host,prefix)

        let { cookie } = this.ctx.request.header;
        let UserAgent = this.ctx.request['user-agent'];
        let headers = {
            'User-Agent': UserAgent
        }
        if(cookie != undefined){
            headers.Cookie = cookie;
        }
    
        //console.log('---------------------');


        //console.log('---------------', headers, '---------------');

        const result = await this.ctx.helper.curl(`${host}${url}`, {
            headers: headers,
            dataType: "json",
            data: params
        });



        this.ctx.status = result.status;
        this.ctx.set(result.headers);
        this.ctx.body = result.data;

    }

    async uploadFile() {

        const stream = await this.ctx.getFileStream();
        const form = new FormStream();
        const { host } = await this.config.apiServer;
        var mimeType = "application/octet-stream";
        let filename = stream.filename;
        form.stream('filename', stream, filename, mimeType);

        let result = await this.ctx.helper.curl(`${host}/file/upload`, {
            method: "POST",
            headers: form.headers(),
            stream: form,
            dataType: 'json',
            timeout: 600000
        })


        this.ctx.body = result.data;
    }


    async captcha() {

        const { host } = await this.config.apiServer;
        
        let result = await this.ctx.curl(`${host}/captcha`, {
            method: 'GET',
            streaming: true
        })

        this.ctx.set(result.headers);
        this.ctx.set('Content-Type','image/jpeg');
        this.ctx.body = result.res;


    }
}


module.exports = zinvest;